import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import BpmnFactory from 'bpmn-js/lib/features/modeling/BpmnFactory'
import { without } from 'min-dash'
import { getBusinessObject, is } from 'bpmn-js/lib/util/ModelUtil'

export function hasProcessRef(element) {
  return is(element, 'bpmn:Participant') && element.businessObject.get('processRef')
}

export function getDocumentValue(element): string {
  return getDocumentation(getBusinessObject(element))
}

export function setDocumentValue(element, value) {
  setDocument(element, getBusinessObject(element), value)
}

export function getProcessDocumentValue(element): string {
  const processRef = getBusinessObject(element).processRef
  return getDocumentation(processRef)
}
export function setProcessDocumentValue(element, value) {
  const processRef = getBusinessObject(element).processRef
  setDocument(element, processRef, value)
}

export function setDocument(element, businessObject, value: string | undefined) {
  const modeling = useModelerStore().getModeling
  const bpmnFactory: BpmnFactory | undefined = useModelerStore().getModeler?.get('bpmnFactory')
  const documentation = findDocumentation(businessObject && businessObject.get('documentation'))
  // (1) 更新或者移除 原有 documentation
  if (documentation) {
    if (value) {
      modeling.updateModdleProperties(element, documentation, { text: value })
    } else {
      modeling.updateModdleProperties(element, businessObject, {
        documentation: without(businessObject.get('documentation'), documentation)
      })
    }
  }
  // (2) 创建新的 documentation
  if (value) {
    const newDocumentation = bpmnFactory?.create('bpmn:Documentation', {
      text: value
    })
    modeling.updateModdleProperties(element, businessObject, {
      documentation: [...businessObject.get('documentation'), newDocumentation]
    })
  }
}

// ////////// helpers
function getDocumentation(businessObject) {
  const documentation = findDocumentation(businessObject && businessObject.get('documentation'))
  return documentation && documentation.text
}

const DOCUMENTATION_TEXT_FORMAT = 'text/plain'

function findDocumentation(docs) {
  return docs.find(function (d) {
    return (d.textFormat || DOCUMENTATION_TEXT_FORMAT) === DOCUMENTATION_TEXT_FORMAT
  })
}
